<?php
/*
 *   This file is part of Verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *   Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */ 

function loadCrontab() {
	$cf = file(CRONTAB_PATH.CRONTAB_FILE);
	$list = array();
	foreach ($cf as $linenum => $line) {
		$el = new stdClass;
		$c = explode(" ",$line);
		if (count($c)==6) {
			$el->id = $linenum;
			$el->minute = $c[0];
			$el->hour = $c[1];
			$el->dom = $c[2];
			$el->month = $c[3];
			$el->dow = $c[4];
			//$el->user = $c[5];
			$el->cmd = preg_replace("/\n/", "", $c[5]);
			$list[$linenum] = $el;			
		}
	}
	return $list;
}

function setCrontab() {
	@exec("crontab ".CRONTAB_PATH.CRONTAB_FILE,$ar,$execret);
	return $execret==0;
}

if ($param['op']=="save") {
	$list = loadCrontab();
	
	$data = json_decode(stripslashes($param['data']));
	
	if ($f = fopen(CRONTAB_PATH.CRONTAB_FILE, 'w')) {
		foreach ($data as $d) {
			if ($d->id!="") {
				//$d->user = CRONTAB_USER;
				$list[$d->id]=$d;
			} else {
				//$d->user = CRONTAB_USER;
				$list[]=$d;
			}
		}

		$cnt = "";
		foreach ($list as $el) {
			if ($cnt!="") $cnt .= "\n";
			//$p = $el->minute." ".$el->hour." ".$el->dom." ".$el->month." ".$el->dow." ".$el->user." ".$el->cmd;
			$p = $el->minute." ".$el->hour." ".$el->dom." ".$el->month." ".$el->dow." ".$el->cmd;
			$cnt .= $p;
			$_log->debug($p);
		}
		$cnt .="\n\n";
		fwrite($f, $cnt);
		fclose($f);
		
		if (!setCrontab()) {
			failed(s("Unable to set contrab file"));			
		} else {
			success();	
		}
	} else {
		failed(s("Unable to open file for write access"));
	}
} else if ($op=="reload") {
	if (!setCrontab()) {
		failed(s("Unable to set contrab file"));			
	} else {
		success();	
	}
} else {
	$list = loadCrontab();
	out(jsonList($list,array("id","minute","hour","dom","month","dow","user","cmd")));
}

?>

 
